
package com.example.testandroid;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.FrameLayout;

import com.example.testandroid.ScoreCounter.ShootPoint;
import com.example.testandroid.TargetPonitAddView.OnPointAddedListener;

public class TargetView extends FrameLayout implements OnPointAddedListener {
    private TargetPonitAddView mPointAddView;
    private TargetBgView mBgView;
    private ScoreCounter mScoreCounter;
    private boolean mIsEditable;
    public PointListener mPointListener;

    public interface PointListener {
        public void onPointAdded(ShootPoint point);
        public void onPointDeleted(ShootPoint point);
    }

    public TargetView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mIsEditable = attrs.getAttributeBooleanValue("TargetView", "isEdit", true);
        init();
    }

    //set Point listener, when point added or removed, notify the listener
    public void setPointListener(PointListener pointListener) {
        this.mPointListener = pointListener;
    }

    public void removeLastPoint() {
        ShootPoint lastPoint = mScoreCounter.getLastShootPoint();
        if (mPointAddView != null) {
            mPointAddView.removeViewAt(mPointAddView.getChildCount() - 1);
        }
        if (mPointListener != null) {
            mPointListener.onPointDeleted(lastPoint);
        }
    }

    private void init() {
        LayoutParams layoutParams = new LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        mBgView = new TargetBgView(getContext(), 6);
        addView(mBgView, layoutParams);
        //add or view. isEditable add, otherwise view
        if (mIsEditable) {
            mPointAddView = new TargetPonitAddView(getContext());
            mPointAddView.setClickable(true);
            mPointAddView.setPointAddedListener(this);
            addView(mPointAddView, layoutParams);
            mScoreCounter = new ScoreCounter(mPointAddView, 6);
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, widthMeasureSpec);
    }

    @Override
    public void onNewPointAdded() {
        ShootPoint point = mScoreCounter.getLastShootPoint();
        if (mPointListener != null) {
            mPointListener.onPointAdded(point);
        }
    }

}
